package com.share.all.rest;

import com.share.all.util.SpringContext;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author:caifan
 * @since 2022/11/27
 */
@Tag(name = "redis参数")
@RestController
@RequestMapping("/redis")
public class RedisRest {

    private final Logger logger = LoggerFactory.getLogger(RedisRest.class);

    private static final String SUCCESS = "success";

    @Autowired
    private RedisTemplate redisTemplate;

    @Operation(summary = "redis设置值")
    @GetMapping("/setValue")
    public String setValue(@RequestParam String key, @RequestParam String value) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value);
        RedisTemplate customRedisTemplate = SpringContext.getBean("customRedisTemplate", RedisTemplate.class);
        if (Objects.nonNull(customRedisTemplate)) {
            ValueOperations customValueOperations = customRedisTemplate.opsForValue();
            customValueOperations.set(key, value);
        }
        return SUCCESS;
    }

    @Operation(summary = "redis获取值")
    @GetMapping
    public String getValue(@RequestParam String key) {
        RedisTemplate customRedisTemplate = SpringContext.getBean("customRedisTemplate", RedisTemplate.class);
        String src = redisTemplate.opsForValue().get(key).toString();
        String values = src;
        if (Objects.nonNull(customRedisTemplate)) {
            values = values.concat(",custom:").concat(customRedisTemplate.opsForValue().get(key).toString());
        }
        logger.info("redis key:{}, value:{}", key, values);
        return values;
    }

}
